package dongnv.poweramp.data;

import java.io.IOException;
import java.util.ArrayList;

import dongnv.poweramp.R;
import dongnv.poweramp.activity.HomeActivity;
import dongnv.poweramp.activity.ListSongPlayActivity;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class ListSongAdapter extends ArrayAdapter<SongItem> {

	public ListSongAdapter(Context context, int textViewResourceId, ArrayList<SongItem> arraySongItem) {
		super(context, textViewResourceId, arraySongItem);
		this.context = context;
		this.arraySongItem = arraySongItem;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final int currentSongIndex = position;
		View view = View.inflate(context, R.layout.song_icon, null);
		songName = (TextView) view.findViewById(R.id.songName);
		songName.setText(arraySongItem.get(position).getName());
		view.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				HomeActivity.systemManager.setCurrentSongItem(arraySongItem.get(currentSongIndex));
				Log.e("", "path: " + HomeActivity.systemManager.getCurrentSongItem().getPath());
				HomeActivity.systemManager.setPlay(true);

				if (HomeActivity.systemManager.getMediaPlayer().isPlaying()) {
					HomeActivity.systemManager.getMediaPlayer().stop();
					HomeActivity.systemManager.getMediaPlayer().reset();
					HomeActivity.systemManager.getMediaPlayer().release();
					HomeActivity.systemManager.removeMediaPlayer();
				}

				try {
					HomeActivity.systemManager.createMediaPlayer();
					HomeActivity.systemManager.getMediaPlayer().setDataSource(HomeActivity.systemManager.getCurrentSongItem().getPath());
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				try {
					HomeActivity.systemManager.getMediaPlayer().prepare();
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				 
				HomeActivity.systemManager.getMediaPlayer().start();
				
				Intent intent = new Intent(context, HomeActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
			} 
		});
		return view;
	}

	private Context context;
	private ArrayList<SongItem> arraySongItem;
	private TextView songName, songPath;
}
